package com.demo.base.auth.douyin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 获取抖音小程序openId
 * @date 2023/3/14 2:39 PM
 */
@Component
@Slf4j
public class DouCode2Session {

    /** 注入抖音配置config */
    private DouConfig douConfig;

    @Autowired
    public void setDouConfig(DouConfig douConfig) {
        this.douConfig = douConfig;
    }

    /**
     * 根据code获取openId
     *
     * @param code
     * @return
     */
    public String getOpenIdByCode(String code) {

        try {
            // 拼接请求url
            String url = douConfig.getUrl();

            // 初始化请求客户端
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            // DefaultHttpClient();
            // POST方式
            HttpPost httpPost = new HttpPost(url);
            CloseableHttpResponse response;

            // 配置信息
            RequestConfig requestConfig =
                    RequestConfig.custom()
                            // 设置连接超时时间(单位毫秒)
                            .setConnectTimeout(5000)
                            // 设置请求超时时间(单位毫秒)
                            .setConnectionRequestTimeout(5000)
                            // socket读写超时时间(单位毫秒)
                            .setSocketTimeout(5000)
                            // 设置是否允许重定向(默认为true)
                            .setRedirectsEnabled(false)
                            .build();

            // 将上面的配置信息 运用到这个Get请求里
            httpPost.setConfig(requestConfig);

            // 设置请求头
            httpPost.addHeader("Content-Type", "application/json");

            // 设置请求参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(douConfig.getAppidPrefix(), douConfig.getAppId());
            jsonObject.put(douConfig.getSecretPrefix(), douConfig.getSecret());
            jsonObject.put(douConfig.getCodePrefix(), code);
            jsonObject.put(douConfig.getAnonymousCodePrefix(), "");
            String body = jsonObject.toJSONString();
            httpPost.setEntity(new StringEntity(body, "UTF-8"));

            // 由客户端执行(发送)POST请求
            response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            log.info("获取抖音openId响应状态为：{}", response.getStatusLine());

            // 获取响应内容
            if (responseEntity == null) {
                log.error("获取抖音小程序openId失败");

                return null;
            }

            // 记录返回结果
            String res = EntityUtils.toString(responseEntity);
            log.info("获取抖音openId响应内容为：{}", res);

            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }

            // 获取openId
            JSONObject jo = JSON.parseObject(res);
            JSONObject jsonData = JSONObject.parseObject(jo.getString("data"));
            String openid = jsonData.getString("openid");
            log.info("抖音小程序登录，openid：{}", openid);

            // 获取openId失败
            if (StringUtils.isBlank(openid)) {
                log.error("获取抖音小程序openId失败，openId为空");

                return null;
            }

            // 返回openId
            return openid;

        } catch (Exception ex) {
            log.error("获取抖音小程序openId失败，原因：{}", ex.getMessage());

            return null;
        }
    }
}
